package com.villaday.idf.fragment;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.AppContext;
import com.villaday.idf.R;
import com.villaday.idf.activity.ChooseCityActity;
import com.villaday.idf.activity.FragmentBackHandler;
import com.villaday.idf.activity.H5AutoTitleActivity;
import com.villaday.idf.activity.SearchBournActivity;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.custom.mzbanner.MZBannerView;
import com.villaday.idf.custom.mzbanner.holder.MZHolderCreator;
import com.villaday.idf.custom.mzbanner.holder.MZViewHolder;
import com.villaday.idf.model.Locations_citiesEntity;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.StatusBarUtil;
import com.villaday.idf.util.TabLayoutUtils;
import com.villaday.idf.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;

import static android.app.Activity.RESULT_OK;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements MZBannerView.BannerPageClickListener, OkHttpUtil.OnDataListener, FragmentBackHandler,ErrorLayout {

    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.banner)
    MZBannerView mMZBanner;
    @BindView(R.id.tab)
    TabLayout tab;
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.tv_choseCity)
    TextView tvChoseCity;
    int i = 1;


    Unbinder unbinder;
    List<String> titles = new ArrayList<>();

    private Gson gson = new GsonBuilder().create();
    private com.villaday.idf.model.advertsEntity advertsEntity;
    private HomeListDynamicFragment homeListDynamicFragment;
    private Object date;
    private Locations_citiesEntity locations_citiesEntity;
    private String currentCityidCurrent;
    private String cityCurrent;
    private StatusLayoutManager statusLayoutManager;
    private int currentPosition=-1;
    private HomeListSaleFragment homeListSaleFragment;
    private HomeListFindFragment homeListFindFragment;
    private List<com.villaday.idf.model.advertsEntity.BodyEntity> list;

    public HomeFragment() {

    }

    public void jump2Page(int page) {

        if (vp != null) {
            vp.setCurrentItem(page, true);
        }

    }

    public static HomeFragment instance() {
        HomeFragment homeFragment = new HomeFragment();
        return homeFragment;
    }

    public void setCity() {
        tvChoseCity.setText(AppContext.cityCurrent);

    }

    public void onRefresh() {
        //StatusBarUtils.setStatusBarLightMode(getActivity(), Color.WHITE);
        StatusBarUtil.setTranslucentForImageViewInFragment(getActivity(), null);
        StatusBarUtil.setLightMode(getActivity());

        //checkVersion();
    }

    @Override
    protected int getViewResId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void init(View v) {
        StatusBarUtil.setTranslucentForImageViewInFragment(getActivity(), null);
        StatusBarUtil.setLightMode(getActivity());

        getdata();

          //设置空白页
        statusLayoutManager = setupDefaultStatusLayoutManager(ll, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                if (currentPosition==0){
                    homeListDynamicFragment.loadData();

                }else if (currentPosition==1){
                    homeListSaleFragment.loadData();

                }else if (currentPosition==2){
                    homeListFindFragment.loadData();

                }
            }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });

    }

    public void getdata() {
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(getContext(), Constant.URL.refresh_token, null, map, this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

    }

    public void intview() {


        titles.clear();


        mMZBanner.getLayoutParams().height = PhoneUtil.getPhoneWidth(getContext()) / 2;
        mMZBanner.requestLayout();
        RefreshtokenEntity.BodyBean roleInfo =
                SharedPreferencesUtil.getRoleInfo(getContext());
        final String roleType = roleInfo.getMember().getType();
        if ("0".equals(roleType)) {
            titles.add("特卖");
            titles.add("发现");
        } else {
            titles.add("动态");
            titles.add("特卖");
            titles.add("发现");
        }


        homeListDynamicFragment = HomeListDynamicFragment.newInstance();
        homeListDynamicFragment.setErrorLayout(this);

        homeListSaleFragment = HomeListSaleFragment.newInstance();
        homeListSaleFragment.setErrorLayout(this);

        homeListFindFragment = HomeListFindFragment.newInstance();
        homeListFindFragment.setErrorLayout(this);

        vp.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                if ("0".equals(roleType)) {
                    return position == 0 ? homeListSaleFragment : homeListFindFragment;

                } else {
                    return position == 0 ? homeListDynamicFragment : position == 1 ? homeListSaleFragment : homeListFindFragment;


                }
                //return HomeListSaleFragment.newInstance();

            }

            @Override
            public int getCount() {
                return titles.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });
        tab.setupWithViewPager(vp);
        TabLayoutUtils.reflex(tab, 13);
    }

    @Override
    protected void loadData() {
        OkHttpUtil.getJSON(getContext(), Constant.URL.adverts + "170000", this);
        getCity();
    }

    public void getCity() {
        OkHttpUtil.getJSON(getContext(), Constant.URL.locations_cities, this);

    }

    private void initBanner(com.villaday.idf.model.advertsEntity advertsEntity) {

        //添加Page点击事件
        mMZBanner.setBannerPageClickListener(this);
        if (advertsEntity.getBody().size() > 1) {
            mMZBanner.setIndicatorVisible(true);
        } else {
            //设置是否显示Indicator
            mMZBanner.setIndicatorVisible(false);
        }

        // 设置数据
        list = new ArrayList<>();
        list.addAll(advertsEntity.getBody());
        /*if (advertsEntity.getBody().size()==1){
            list.addAll(advertsEntity.getBody());
            list.addAll(advertsEntity.getBody());
        }
        if (advertsEntity.getBody().size()==2){
            list.add(advertsEntity.getBody().get(0));

        }*/
        mMZBanner.setPages(list, new MZHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });

        if (list.size()>1){
            mMZBanner.start();
        }

        // 设置页面改变监听器
        mMZBanner.addPageChangeLisnter(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    @Override
    public void onPause() {
        super.onPause();
        mMZBanner.pause();//暂停轮播
    }

    @Override
    public void onResume() {
        super.onResume();
        if (list!=null&&list.size()>1){
            mMZBanner.start();
        }
    }

    @Override //banner添加Page点击事件
    public void onPageClick(View view, int position) {
        if (!TextUtils.isEmpty(advertsEntity.getBody().get(position).getUrl())) {
            Intent intent = new Intent(getContext(), H5AutoTitleActivity.class);
            intent.putExtra("title", "爱订房");

            intent.putExtra("url", advertsEntity.getBody().get(position).getUrl());

            startActivity(intent);
        }

    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if ((Constant.URL.adverts + "170000").equals(url)) {
                LogeUtil.e("adverts", json);
                advertsEntity = gson.fromJson(json, com.villaday.idf.model.advertsEntity.class);
                if ("200".equals(advertsEntity.getCode())) {
                    initBanner(advertsEntity);
                }

            } else if (Constant.URL.refresh_token.equals(url)) { //刷新Token
                LogeUtil.e("refresh_token", json);
                RefreshtokenEntity refreshtoken = gson.fromJson(json, RefreshtokenEntity.class);
                if (Constant.Strings.SUC.equals(refreshtoken.getCode())) {
                    //改变 主页bottom vip 图标及文字颜色
                    mRxManager.post(getResources().getString(R.string.ChangeMainBotton_vip_dirwableAndColor),refreshtoken.getBody().getMember().getType());

                    SharedPreferencesUtil.saveRoleInfo(getContext(), json);
                    SharedPreferencesUtil.saveToken(getContext(), refreshtoken.getBody().getToken());
                    intview();
                } else {
                    ToastUtil.initToast(getContext(), refreshtoken.getMsg());
                }
            } else if (Constant.URL.locations_cities.equals(url)) {
                LogeUtil.e("locations_cities", json);
                locations_citiesEntity = gson.fromJson(json, Locations_citiesEntity.class);
                if ("200".equals(locations_citiesEntity.getCode()) && locations_citiesEntity.getBody() != null) {
                    OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.surrounds_cities, locations_citiesEntity.getBody().getId()), this);
                    if (!TextUtils.isEmpty(AppContext.currentCityidCurrent)) {
                        currentCityidCurrent = AppContext.currentCityidCurrent;
                        cityCurrent = AppContext.cityCurrent;
                    } else {
                        currentCityidCurrent = locations_citiesEntity.getBody().getId();
                        cityCurrent = locations_citiesEntity.getBody().getName();
                        AppContext.currentCityidCurrent = currentCityidCurrent;//当前城市id
                        AppContext.cityCurrent = cityCurrent;//当前城市
                    }

                }
            }
        }
    }

    @Override
    public void onFailure(String url, String error) {
       // loadData();
    }

    @OnClick({R.id.tv_choseCity, R.id.tv_play, R.id.ll_fstoresearch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_choseCity: {//搜索城市
                if (locations_citiesEntity != null && locations_citiesEntity.getBody() != null) {
                    Intent intent = new Intent(getContext(), ChooseCityActity.class);
                    intent.putExtra("cityId", currentCityidCurrent);
                    startActivityForResult(intent, 123);
                }

            }
            break;
            case R.id.ll_fstoresearch: {//搜索目的地
                Intent intent = new Intent(getContext(), SearchBournActivity.class);
                intent.putExtra("cityId", currentCityidCurrent);
                startActivityForResult(intent, 124);
            }
            break;

            case R.id.tv_play:
                Intent intent1 = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + "0755-26657792");
                intent1.setData(data);
                startActivity(intent1);
                break;
        }


    }

    @Override
    public boolean onBackPressed() {

        return homeListDynamicFragment.onBackPressed();
    }

    public Object getdate() {
        return date;
    }

    @Override
    public void setError(int position) {
        currentPosition = position;
        statusLayoutManager.showErrorLayout();

    }

    @Override
    public void setSuccess() {
        statusLayoutManager.showSuccessLayout();

    }


    public static class BannerViewHolder implements MZViewHolder<com.villaday.idf.model.advertsEntity.BodyEntity> {
        private SimpleDraweeView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item_5, null);
            mImageView = (SimpleDraweeView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, com.villaday.idf.model.advertsEntity.BodyEntity data) {
            // 数据绑定
            // mImageView.setImageURI(new Uri.Builder().scheme("res").path(String.valueOf(data)).build());
            mImageView.setImageURI(data.getMaterial().getUrl());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 123) {//城市搜索
                currentCityidCurrent = data.getStringExtra("cityId");
                cityCurrent = data.getStringExtra("cityName");
                tvChoseCity.setText(cityCurrent);

                AppContext.currentCityidCurrent = data.getStringExtra("cityId");
                AppContext.cityCurrent = data.getStringExtra("cityName");
            }
        }
    }

}
